package socket.nio.demo_02;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.SocketChannel;

/**
 * 视图缓冲区
 */
public class IntgenClient {
    public static final int port = 1024;

    public static void main(String[] args) {
        try {
            InetSocketAddress address = new InetSocketAddress(port);
            SocketChannel channel = SocketChannel.open(address);
            ByteBuffer buffer = ByteBuffer.allocate(4);
            IntBuffer view = buffer.asIntBuffer();

            for(int expected = 0; ;expected++) {
                channel.read(buffer);
                int actual = view.get();
                buffer.clear();
                view.rewind();

                if(actual != expected) {
                    System.out.println("Expected " + expected + "; was " + actual);
                    break;
                }

                System.out.println(actual);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
